<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SiliconFlow 聊天应用</title>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      line-height: 1.6;
      color: #333;
      background-color: #f5f5f5;
      display: flex;
      flex-direction: column;
      height: 100vh;
    }
    
    .container {
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      flex: 1;
      display: flex;
      flex-direction: column;
    }
    
    .header {
      text-align: center;
      margin-bottom: 20px;
      padding: 10px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }
    
    .header h1 {
      color: #2c3e50;
      font-size: 24px;
    }
    
    .chat-container {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }
    
    .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
    }
    
    .message {
      margin-bottom: 15px;
      display: flex;
    }
    
    .message.user {
      justify-content: flex-end;
    }
    
    .message-content {
      max-width: 70%;
      padding: 10px 15px;
      border-radius: 18px;
      word-break: break-word;
    }
    
    .user .message-content {
      background-color: #1e88e5;
      color: white;
      border-top-right-radius: 4px;
    }
    
    .assistant .message-content {
      background-color: #f1f1f1;
      color: #333;
      border-top-left-radius: 4px;
    }
    
    .input-area {
      display: flex;
      padding: 15px;
      background-color: #f9f9f9;
      border-top: 1px solid #eee;
    }
    
    #message-input {
      flex: 1;
      padding: 12px 15px;
      border: 1px solid #ddd;
      border-radius: 20px;
      font-size: 16px;
      outline: none;
      transition: border-color 0.3s;
    }
    
    #message-input:focus {
      border-color: #1e88e5;
    }
    
    #send-button {
      margin-left: 10px;
      padding: 0 20px;
      background-color: #1e88e5;
      color: white;
      border: none;
      border-radius: 20px;
      font-size: 16px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    
    #send-button:hover {
      background-color: #1976d2;
    }
    
    #send-button:disabled {
      background-color: #b0bec5;
      cursor: not-allowed;
    }
    
    .controls {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
    
    #clear-button {
      padding: 8px 15px;
      background-color: #f44336;
      color: white;
      border: none;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    
    #clear-button:hover {
      background-color: #d32f2f;
    }
    
    .loading {
      display: none;
      text-align: center;
      padding: 10px;
      font-style: italic;
      color: #757575;
    }
    
    .typing-indicator {
      display: inline-block;
      width: 50px;
      text-align: left;
    }
    
    .typing-indicator span {
      display: inline-block;
      width: 8px;
      height: 8px;
      background-color: #757575;
      border-radius: 50%;
      animation: typing 1.4s infinite both;
      margin: 0 2px;
    }
    
    .typing-indicator span:nth-child(2) {
      animation-delay: 0.2s;
    }
    
    .typing-indicator span:nth-child(3) {
      animation-delay: 0.4s;
    }
    
    @keyframes typing {
      0% {
        transform: translateY(0);
      }
      50% {
        transform: translateY(-5px);
      }
      100% {
        transform: translateY(0);
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>SiliconFlow 聊天应用</h1>
    </div>
    
    <div class="chat-container">
      <div class="chat-messages" id="chat-messages">
        <div class="message assistant">
          <div class="message-content">
            你好！我是基于SiliconFlow API的AI助手。有什么我可以帮助你的吗？
          </div>
        </div>
      </div>
      
      <div class="loading" id="loading">
        <div class="typing-indicator">
          <span></span>
          <span></span>
          <span></span>
        </div>
        AI正在思考中...
      </div>
      
      <div class="input-area">
        <input type="text" id="message-input" placeholder="输入你的问题..." autocomplete="off">
        <button id="send-button">发送</button>
      </div>
    </div>
    
    <div class="controls">
      <button id="clear-button">清除对话历史</button>
    </div>
  </div>
  
  <script>
    // 生成唯一会话ID
    function generateSessionId() {
      return 'session-' + Math.random().toString(36).substring(2, 15);
    }
    
    // 获取或创建会话ID
    let sessionId = localStorage.getItem('chatSessionId');
    if (!sessionId) {
      sessionId = generateSessionId();
      localStorage.setItem('chatSessionId', sessionId);
    }
    
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    const clearButton = document.getElementById('clear-button');
    const chatMessages = document.getElementById('chat-messages');
    const loadingIndicator = document.getElementById('loading');
    
    // 发送消息到服务器
    async function sendMessage(message) {
      try {
        // 显示加载指示器
        loadingIndicator.style.display = 'block';
        
        const response = await fetch('/api/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            message,
            sessionId
          })
        });
        
        const data = await response.json();
        
        // 隐藏加载指示器
        loadingIndicator.style.display = 'none';
        
        if (data.error) {
          throw new Error(data.error);
        }
        
        // 添加AI回复到聊天界面
        addMessage(data.response, 'assistant');
        
      } catch (error) {
        // 隐藏加载指示器
        loadingIndicator.style.display = 'none';
        
        console.error('发送消息错误:', error);
        alert('发送消息失败: ' + error.message);
      }
    }
    
    // 添加消息到聊天界面
    function addMessage(content, role) {
      const messageDiv = document.createElement('div');
      messageDiv.className = `message ${role}`;
      
      const messageContent = document.createElement('div');
      messageContent.className = 'message-content';
      messageContent.textContent = content;
      
      messageDiv.appendChild(messageContent);
      chatMessages.appendChild(messageDiv);
      
      // 滚动到底部
      chatMessages.scrollTop = chatMessages.scrollHeight;
    }
    
    // 清除聊天历史
    async function clearChatHistory() {
      try {
        const response = await fetch('/api/clear-context', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ sessionId })
        });
        
        const data = await response.json();
        
        if (data.success) {
          // 清除聊天界面
          chatMessages.innerHTML = '';
          
          // 添加欢迎消息
          addMessage('你好！我是基于SiliconFlow API的AI助手。有什么我可以帮助你的吗？', 'assistant');
        } else {
          throw new Error(data.message || '清除历史失败');
        }
        
      } catch (error) {
        console.error('清除历史错误:', error);
        alert('清除历史失败: ' + error.message);
      }
    }
    
    // 发送按钮点击事件
    sendButton.addEventListener('click', () => {
      const message = messageInput.value.trim();
      
      if (message) {
        // 添加用户消息到聊天界面
        addMessage(message, 'user');
        
        // 清空输入框
        messageInput.value = '';
        
        // 发送消息到服务器
        sendMessage(message);
      }
    });
    
    // 输入框回车事件
    messageInput.addEventListener('keypress', (event) => {
      if (event.key === 'Enter') {
        sendButton.click();
      }
    });
    
    // 清除按钮点击事件
    clearButton.addEventListener('click', clearChatHistory);
    
    // 页面加载时聚焦输入框
    window.addEventListener('load', () => {
      messageInput.focus();
    });
  </script>
</body>
</html>